package com.cloudptt.api.timer;

import java.util.Timer;
import java.util.TimerTask;

import android.os.Handler;
import android.os.Message;


public class SysTimer
{
	private Timer timer = null;
	private TimeoutListener listener = null;

	public SysTimer(int seconds,TimeoutListener listener)
	{
		this.timer = new Timer();  
		TimerTask task = new TimeInTask();
		this.timer.schedule(task, seconds * 1000); 
		
		this.listener = listener;
	}

	public void cancelTimer()
	{
		if(this.timer != null)
		{
			this.timer.cancel();
			this.timer = null;
		}
	}

	public void onTimeout()
	{
		if(listener != null)
		{
			listener.onTimeout();
			listener = null;
		}
		cancelTimer();
		mHandler = null;
	}

	private final static int MsgId_Rollback = 1;
	private  Handler mHandler = new Handler(){ 
		@Override
		public void handleMessage(Message msg)
		{
			if(msg.what == MsgId_Rollback)
			{
				onTimeout(); 
			}
		}
	};
	
	class TimeInTask extends TimerTask 
	{  
		@Override  
		public void run() {  
			// 需要做的事:发送消息  
			cancelTimer();
			
			Message msg = mHandler.obtainMessage(MsgId_Rollback);
			msg.sendToTarget();
		}  
	}
}
